#include <lib3d/anim2d/FrameTimes.h>

#include <system/assert.h>

namespace liba {
namespace lib3d {
namespace anim2d {

FrameTimes::FrameTimes()
	: duration(0)
{ }

FrameTimes::FrameTimes(size_t amount)
	: duration(0)
{ 
	timings.reserve(amount);
}

FrameTimes::FrameTimes(const FrameTimes& rhs)
	: timings(rhs.timings)
	, duration(rhs.duration)
{ }

const FrameTimes& FrameTimes::operator=(const FrameTimes& rhs)
{
	if (&rhs != this)
	{
		this->duration = rhs.duration;
		this->timings = rhs.timings;
	}

	return *this;
}

FrameTimes::~FrameTimes()
{ }

void FrameTimes::Reset()
{
	timings.clear();

	duration = 0.0;
}

void FrameTimes::AddFrame(double time)
{
	timings.push_back(this->duration);
	this->duration += time;
}

size_t FrameTimes::GetFrameNumber(double time) const
{
	if (this->timings.empty())
		return 0;

	if (time <= this->timings.front())
		return 0;

	if (time >= this->timings.back())
		return timings.size() - 1;

	for (size_t i = 1; i < this->timings.size(); ++i)
	{
		if (timings[i] > time)
			return i - 1;
	}

	LIBA_FAIL_UNEXPECTED();
	return 0;
}

size_t FrameTimes::GetFrameCount() const
{
	return this->timings.size();
}

double FrameTimes::GetTime(size_t frameNumber) const
{
	if (frameNumber >= timings.size())
		return duration;

	return timings[frameNumber];
}

} // namespace anim2d
} // namespace lib3d
} // namespace liba